import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import '../../api/api_methods.dart';
import '../../model/DetailsProductModel.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_html/flutter_html.dart';
import '../../provide/shopping_cart.dart';
import 'package:provide/provide.dart';
import '../../provide/current_Index_provide.dart';

class DetailsProductPage extends StatefulWidget {
  final String id;

  const DetailsProductPage({Key key, this.id}) : super(key: key);

  @override
  _DetailsProductPageState createState() => _DetailsProductPageState();
}

class _DetailsProductPageState extends State<DetailsProductPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  var future;
  DetailsProductModel model;

  @override
  void initState() {
    var formData = {'goodId': widget.id};
    future = request("getGoodDetailById", formData: formData);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: future,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasData) {
          debugPrint("${snapshot.data.toString()}");
          var data = json.decode(snapshot.data.toString());
          model = DetailsProductModel.fromJson(data);
          return Stack(
            children: <Widget>[
              _buildWidget(),
              Positioned(bottom: 0, left: 0, right: 0, child: _buildBottomWidget())
            ],
          );
        } else {
          return Center(
            child: SpinKitFadingCircle(
              itemBuilder: (_, int index) {
                return DecoratedBox(
                  decoration: BoxDecoration(
                    color: index.isEven ? Colors.red : Colors.green,
                  ),
                );
              },
            ),
          );
        }
      },
    );
  }

  Widget _buildList() {
    return Material(
      child: Container(
        child: ListView(
          children: <Widget>[
            Container(
              width: double.infinity,
              color: Colors.white,
              child: CachedNetworkImage(
                  height: ScreenUtil().setHeight(600),
                  imageUrl: model.detailsGoods.goodInfo?.image1,
                  fit: BoxFit.cover),
            ),
            ListTile(
              title: Text(
                "${model.detailsGoods.goodInfo.goodsName}",
                style: TextStyle(color: Colors.red, fontSize: ScreenUtil().setSp(35)),
              ),
              subtitle: Text(
                "编号：${model.detailsGoods.goodInfo.goodsSerialNumber}",
                style: TextStyle(color: Colors.grey[400]),
              ),
            ),
            ListTile(
                title: Text(
                  "￥ ${model.detailsGoods.goodInfo.presentPrice}",
                  style: TextStyle(
                      color: Colors.red,
                      fontSize: ScreenUtil().setSp(35),
                      fontWeight: FontWeight.bold),
                ),
                subtitle: RichText(
                  text: TextSpan(
                    text: '市场价 ',
                    style: TextStyle(fontWeight: FontWeight.bold, color: Colors.grey[400]),
                    children: <TextSpan>[
                      TextSpan(
                        text: '￥ ${model.detailsGoods.goodInfo.oriPrice}',
                        style: TextStyle(
                          decoration: TextDecoration.lineThrough,
                        ),
                      )
                    ],
                  ),
                )),
            Container(height: 4, color: Colors.white),
            ListTile(
              title: Text(
                "说明:>急速送达>正品保证",
                style: TextStyle(color: Colors.red, fontSize: ScreenUtil().setSp(28)),
              ),
            ),
          ],
        ),
      ),
    );
  }

  //商品顶部信息
  Widget _buildTopWidget() {
    return ListView(
      children: <Widget>[
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              width: double.infinity,
              color: Colors.white,
              child: CachedNetworkImage(
                  height: ScreenUtil().setHeight(650),
                  imageUrl: model.detailsGoods.goodInfo?.image1,
                  fit: BoxFit.cover),
            ),
            SizedBox(height: ScreenUtil().setHeight(30)),
            Padding(
              padding: const EdgeInsets.only(left: 16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    "${model.detailsGoods.goodInfo.goodsName}",
                    style: TextStyle(color: Colors.white, fontSize: ScreenUtil().setSp(35)),
                  ),
                  Text(
                    "编号：${model.detailsGoods.goodInfo.goodsSerialNumber}",
                    style: TextStyle(color: Colors.grey[300]),
                  ),
                  SizedBox(height: ScreenUtil().setHeight(18)),
                  Row(
                    children: <Widget>[
                      Text(
                        "￥ ${model.detailsGoods.goodInfo.presentPrice}",
                        style: TextStyle(color: Colors.white, fontSize: ScreenUtil().setSp(35)),
                      ),
                      SizedBox(width: ScreenUtil().setWidth(40)),
                      Text("市场价：", style: TextStyle(color: Colors.white)),
                      Text(
                        "￥ ${model.detailsGoods.goodInfo.oriPrice}",
                        style: TextStyle(
                            decoration: TextDecoration.lineThrough, color: Colors.grey[300]),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
        Padding(
          padding: EdgeInsets.symmetric(vertical: 16),
          child: Container(
            width: double.infinity,
            padding: EdgeInsets.all(16),
            child: Text(
              "说明:>急速送达>正品保证",
              style: TextStyle(color: Colors.white, fontSize: ScreenUtil().setSp(28)),
            ),
          ),
        ),
      ],
    );
  }

  //底部添加购物车
  Widget _buildBottomWidget() {
    return Material(
      child: Container(
        width: double.infinity,
        height: ScreenUtil().setHeight(100),
        color: Colors.white,
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 2,
              child: Stack(
                children: <Widget>[
                  Container(
                    alignment: Alignment.center,
                    height: ScreenUtil().setHeight(100),
                    child: IconButton(
                      icon: Icon(Icons.shopping_cart),
                      iconSize: 35,
                      color: Colors.redAccent,
                      onPressed: () {
                        Provide.value<CurrentIndexProvide>(context).changeIndex(2);
                        Navigator.pop(context);
                      },
                    ),
                  ),
                  Provide<ShoppingCartProvide>(builder: (context, child, scope) {
                    int goodsCount = Provide.value<ShoppingCartProvide>(context).allCount;
                    return Positioned(
                      child: CircleAvatar(
                        backgroundColor: Colors.redAccent,
                        radius: 10.0,
                        child: Text(
                          "$goodsCount",
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: ScreenUtil().setSp(20),
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                      top: 10,
                      right: 0,
                      left: 30,
                    );
                  }),
                ],
              ),
            ),
            Expanded(
                flex: 3,
                child: InkWell(
                  child: Container(
                    alignment: Alignment.center,
                    width: double.infinity,
                    height: double.infinity,
                    color: Colors.green,
                    child: Text(
                      "加入购物车",
                      style: TextStyle(color: Colors.white, fontSize: ScreenUtil().setSp(30)),
                    ),
                  ),
                  onTap: () async {
                    await Provide.value<ShoppingCartProvide>(context).save(
                        model.detailsGoods.goodInfo.goodsId,
                        model.detailsGoods.goodInfo.goodsName,
                        1,
                        model.detailsGoods.goodInfo.presentPrice,
                        model.detailsGoods.goodInfo.image1);
                  },
                )),
            Expanded(
                flex: 3,
                child: InkWell(
                  child: Container(
                    alignment: Alignment.center,
                    width: double.infinity,
                    height: double.infinity,
                    color: Colors.red,
                    child: Text(
                      "立即购买",
                      style: TextStyle(color: Colors.white, fontSize: ScreenUtil().setSp(30)),
                    ),
                  ),
                  onTap: () async {
                    await Provide.value<ShoppingCartProvide>(context).remove();
                  },
                )),
          ],
        ),
      ),
    );
  }

  //商品信息展示、详情及评价
  Widget _buildWidget() {
    List<String> _tabs = ['详情', '评价'];
    return DefaultTabController(
      length: _tabs.length, // This is the number of tabs.
      child: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            SliverOverlapAbsorber(
              handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
              child: SliverAppBar(
                title: Text(
                  '${model.detailsGoods.goodInfo.goodsName}',
                ),
                pinned: true,
                forceElevated: innerBoxIsScrolled,
                expandedHeight: ScreenUtil().setHeight(1000),
                flexibleSpace: FlexibleSpaceBar(
                  background: _buildList(),
                ),
                bottom: TabBar(
                  labelColor: Colors.black,
                  indicatorColor: Colors.black,
                  indicatorWeight: 3,
                  tabs: _tabs.map((String name) => Tab(text: name)).toList(),
                ),
              ),
            ),
          ];
        },
        body: TabBarView(
          children: _tabs.map((String name) {
            return SafeArea(
              top: false,
              bottom: false,
              child: Builder(
                builder: (BuildContext context) {
                  return CustomScrollView(
                    key: PageStorageKey<String>(name),
                    slivers: <Widget>[
                      SliverOverlapInjector(
                        handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                      ),
                      SliverList(
                        delegate: SliverChildBuilderDelegate(
                          (BuildContext context, int index) {
                            return (name.contains("详情"))
                                ? Html(data: model.detailsGoods.goodInfo.goodsDetail)
                                : Column(
                                    children: <Widget>[
                                      (model.detailsGoods.goodComments.length == 0)
                                          ? Material(
                                              child: Container(
                                              padding: EdgeInsets.all(16),
                                              width: double.infinity,
                                              child: Text(
                                                "——— 暂无评论 ———",
                                                style: TextStyle(
                                                    color: Colors.grey[400],
                                                    fontSize: ScreenUtil().setSp(30)),
                                                textAlign: TextAlign.center,
                                              ),
                                            ))
                                          : Container(color: Colors.green, height: 50),
                                      CachedNetworkImage(
                                        imageUrl: model.detailsGoods.advertesPicture.pICTUREADDRESS,
                                        fit: BoxFit.cover,
                                      ),
                                    ],
                                  );
                          },
                          childCount: 1,
                        ),
                      ),
                    ],
                  );
                },
              ),
            );
          }).toList(),
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
